package com.huanzhidadi.springsecurity.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 把token信息通过feign传递给其它服务
 */
@Slf4j
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            if (request != null) {
                log.info("FeignConfiguration 请求来源: {}", request.getRequestURI());
                log.info("feignTarget type: {}, name: {}, url: {}", template.feignTarget().type().getName(), template.feignTarget().name(), template.feignTarget().url());
                log.info("methodMetadata: {}", template.methodMetadata().configKey());
                String authorization = request.getHeader("token");
                if (StringUtils.isBlank(authorization)) {
                    authorization = (String) request.getAttribute("token");
                }
                template.header("token", authorization);
            }
        }
    }
}
